<?php
/**
 * Controller to manage product categories in admin area
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @package Products Module
 * @license  New BSD License
 * 
 */
class admin_ProductcategoriesController extends Bel_Controller_Tree {
	
	/**
	 * Categories model
	 *
	 * @var Models_ProductCategories
	 */
	protected $_tree;
	
	/**
	 * Initialization
	 *
	 */
	public function init() {
		$this->_formdata = new Zend_Session_Namespace ( 'formdata' );
		$this->_tree_template = 'products/categories/default.tpl';
		$this->_move_form_template = 'products/categories/move_node.tpl';
		$this->_formname = 'catalog_form';		
		$this->_tree = new Models_ProductCategories();
		parent::init ();
	}
	
	/**
	 * Adds node to categories table. Handles category image upload.
	 *
	 */
	public function addnodeAction(){		
		$uploadedFile = $this->_handleUpload();
		if($uploadedFile){
			$this->_request->setParam('category_image','tmp/categories/'.basename($uploadedFile));
		}
		parent::addnodeAction();
	}
	
	/**
	 * Edits category node. Handles category image upload.
	 *
	 */
	public function editnodeAction(){
		$uploadedFile = $this->_handleUpload();
		if($uploadedFile){
			$node = $this->_tree->getNodeInfo($this->_request->getParam('category_id'));
			@unlink(HOME_DIR.$node->category_image);
			$this->_request->setParam('category_image','tmp/categories/'.basename($uploadedFile));
		}		
		parent::editnodeAction();
	}
	
	/**
	 * Deletes category branch. Also deletes category images.
	 *
	 */
	public function deletebranchAction(){
		$branchToDelete = $this->_tree->getTreeBranch($this->_request->getParam('category_id'));
		foreach($branchToDelete as $node){
			if($node->category_image){
				@unlink(HOME_DIR.'tmp'.DS.'categories'.DS.$node->category_image);
			}
		}
		parent::deletebranchAction();
	}
	
	/**
	 * Handles category image upload
	 *
	 * @return array - array of pathes to uploaded files || redirects to category add/modify form - in case of error
	 */
	private function _handleUpload(){
		$uploader = new Bel_File_Uploader();
		$uploader->setDestination(HOME_DIR.'tmp/categories');
		$uploader->ignoreNoFile(true);
		$uploader->isImage();
		
		if($uploader->upload()){
			if($uploader->isReceived() && $uploader->isUploaded()){
				return $uploader->getFileName();
			}else{
				return false;
			}
		}else{
			foreach($uploader->getMessages() as $error){
				$this->_messages->setMessage($error,'error');
			}
			$this->_redirect($this->_add_form_action.'category_id/'.$this->_request->getParam('category_id'));
			return null;			
		}
		return null;
	}	
}